package vamp_serviceweb

import org.springframework.dao.DataIntegrityViolationException

class PoiController {

    static allowedMethods = [save: "POST", update: "POST", delete: "POST"]

    def geocoderService

    def index() {
        redirect(action: "list", params: params)
    }

    def list() {
        params.max = Math.min(params.max ? params.int('max') : 10, 100)
        [poiInstanceList: Poi.list(params), poiInstanceTotal: Poi.count()]
    }

    def create() {
        [poiInstance: new Poi(params)]
    }

    def save() {
        def poiInstance = new Poi(params)

        if (session.member != null){
            poiInstance.membre = session.member
        }else{
            redirect(controller: member, action: "login")
        }
        //Creation et ajout d'une address
        def addressInstance = new Address(line1:  params.line1, line2 : params.line2, line3: params.line3, zipCode: params.zipCode, city: params.city, country: params.country)
        String addr = params.line1+" "+params.line2+" "+params.line3+" "+params.zipCode+" "+params.city+" "+params.country
        println("address : "+addr)
        //Récupération des coordonnée GPS via googlemap
        def result = geocoderService.reverseGeocode(addr)
        //result ==> result.lat et result.lng
        println "Latitude: ${result.lat}"
        println  "Longitude: ${result.lng}"
        def gpslocationInstance = new Gpslocation(latitude: result.lat, longitude: result.lng)
        addressInstance.gpslocation = gpslocationInstance
        poiInstance.address = addressInstance
        gpslocationInstance.save()
        addressInstance.save()
        //creation d'un link avec upload de fichier
        def uploadedFile = request.getFile('payload')
        if(!uploadedFile.empty){
            println "Class: ${uploadedFile.class}"
            println "Name: ${uploadedFile.name}"
            println "OriginalFileName: ${uploadedFile.originalFilename}"
            println "Size: ${uploadedFile.size}"
            println "ContentType: ${uploadedFile.contentType}"
            def webRootDir = servletContext.getRealPath("/")
            def userDir = new File(webRootDir, "/payload/${session.member.firstName}")
            userDir.mkdirs()
            uploadedFile.transferTo(new File(userDir, uploadedFile.originalFilename))

            poiInstance.imgurl = uploadedFile.originalFilename
            //Creation d'un link un link peut avoir un poi et non l'inverse
            def linkInstance = new Link(poi: poiInstance, uri: webRootDir+uploadedFile.originalFilename)
            linkInstance.save()
        }

        if (!poiInstance.save(flush: true)) {
            render(view: "create", model: [poiInstance: poiInstance])
            return
        }

        flash.message = message(code: 'default.created.message', args: [message(code: 'poi.label', default: 'Poi'), poiInstance.id])
        redirect(action: "show", id: poiInstance.id)
    }

    def show() {
        def poiInstance = Poi.get(params.id)
        println(poiInstance.description)
        if (!poiInstance) {
            flash.message = message(code: 'default.not.found.message', args: [message(code: 'poi.label', default: 'Poi'), params.id])
            redirect(action: "list")
            return
        }

        [poiInstance: poiInstance]
    }

    def edit() {
        def poiInstance = Poi.get(params.id)
        def addressInstance = poiInstance.address
        if (!poiInstance) {
            flash.message = message(code: 'default.not.found.message', args: [message(code: 'poi.label', default: 'Poi'), params.id])
            redirect(action: "list")
            return
        }

        [poiInstance: poiInstance]
    }

    def update() {
        def poiInstance = Poi.get(params.id)
        if (!poiInstance) {
            flash.message = message(code: 'default.not.found.message', args: [message(code: 'poi.label', default: 'Poi'), params.id])
            redirect(action: "list")
            return
        }

        if (params.version) {
            def version = params.version.toLong()
            if (poiInstance.version > version) {
                poiInstance.errors.rejectValue("version", "default.optimistic.locking.failure",
                        [message(code: 'poi.label', default: 'Poi')] as Object[],
                        "Another user has updated this Poi while you were editing")
                render(view: "edit", model: [poiInstance: poiInstance])
                return
            }
        }
        def addressInstance = poiInstance.address
        addressInstance.properties = params
        addressInstance.save()
        poiInstance.properties = params

        if (!poiInstance.save(flush: true)) {
            render(view: "edit", model: [poiInstance: poiInstance])
            return
        }

        flash.message = message(code: 'default.updated.message', args: [message(code: 'poi.label', default: 'Poi'), poiInstance.id])
        redirect(action: "show", id: poiInstance.id)
    }

    def delete() {
        def poiInstance = Poi.get(params.id)
        if (!poiInstance) {
            flash.message = message(code: 'default.not.found.message', args: [message(code: 'poi.label', default: 'Poi'), params.id])
            redirect(action: "list")
            return
        }

        try {
            poiInstance.delete(flush: true)
            flash.message = message(code: 'default.deleted.message', args: [message(code: 'poi.label', default: 'Poi'), params.id])
            redirect(action: "list")
        }
        catch (DataIntegrityViolationException e) {
            flash.message = message(code: 'default.not.deleted.message', args: [message(code: 'poi.label', default: 'Poi'), params.id])
            redirect(action: "show", id: params.id)
        }
    }

    def myPoi(){
        if (session.member == null){
            println("params"+params.id)
            params.max = Math.min(params.max ? params.int('max') : 10, 100)
            [poiInstanceList: Poi.findAllWhere(membre: Member.get(params.id)), poiInstanceTotal: Poi.count()]
        }else{
            params.max = Math.min(params.max ? params.int('max') : 10, 100)
            [poiInstanceList: Poi.findAllWhere(membre: session.member), poiInstanceTotal: Poi.count()]
        }
    }
}
